#include "kbox_hash.h"

hashtable_t *hash = NULL;

int KBoxHashCreate()
{
    hash = (hashtable_t *)KBoxMalloc(sizeof(hashtable_t));
    if (!hash)
        return -1;

    memset(hash, 0, sizeof(hashtable_t));
    return init_hashtable(hash);
}

void KBoxHashDestory()
{
    dest_hashtable(hash);
    if (hash)
        KBoxFree(hash);
}

int KBoxHashSet(char *key, char *value)
{
    return put_kv_hashtable(hash, key, value);
}

char *KBoxHashGet(char *key)
{
    return get_kv_hashtable(hash, key);
}

int KBoxHashDelete(char *key)
{
    return delete_kv_hashtable(hash, key);
}

int KBoxHashModify(char *key, char *value)
{
    if (!hash || !key || !value)
        return -1;

    int idx = _hash(key, MAX_TABLE_SIZE);

    hashnode_t *node = hash->nodes[idx];

    while (node != NULL)
    {

        if (strcmp(node->key, key) == 0)
        {
            KBoxFree(node->value);

            node->value = KBoxMalloc(strlen(value) + 1);
            if (node->value)
            {
                strcpy(node->value, value);
                return 0;
            }
            else
                assert(0);
        }
        node = node->next;
    }

    return -1;
}

int KBoxHashCount()
{
    return hash->count;
}
